package summit.tests
{
import flash.events.Event;

import summit.basecamp.constants.CategoryFilter;
import summit.basecamp.helpers.CategoryHelper;
import summit.data.AccountToken;
import summit.events.BasecampAPIEvent;
import summit.net.BasecampRequest;
import summit.tests.tools.SummitTestContainer;
import summit.tests.tools.TestHelpers;

public class CategoryHelperTests extends SummitTestContainer
{
	private var _categoryId:String;
	private var _types:Array = 
	[CategoryFilter.POST, CategoryFilter.ATTACHMENT];
	private var _listIndex:int = 0;
	
	public function CategoryHelperTests(token:AccountToken)
	{
		super(token);
	}
	
	override protected function self_CompleteInit(e:Event):void
	{
		super.initializeLoader(loader_OKPrepare);
		loader.load(CategoryHelper.prepare(projectId));
	}
	
	override public function cleanUp():void
	{
		super.initializeLoader(loader_OKDelete);
		loader.load(CategoryHelper.destroy(_categoryId));
	}
	
	public function readTest(context:Object):void
	{
		super.initializeLoader(super.loader_OKComplete);
		loader.load(CategoryHelper.read(_categoryId));	
	}
	
	public function listTest(context:Object):void
	{
		// need to disconnect the normal finish signal
		super.initializeLoader(loader_OKList);
		loader.load(CategoryHelper.list(projectId)); // default
	}
	
	public function updateTest(context:Object):void
	{
		super.initializeLoader(loader_OKUpdateRead);
		loader.load(CategoryHelper.read(_categoryId));
	}
	
	private function loader_OKUpdateRead(e:BasecampAPIEvent):void
	{
		super.initializeLoader(loader_OKComplete);
		loader.load(CategoryHelper.update(e.data));
	}
	
	private function loader_OKList(e:BasecampAPIEvent):void
	{
		if(_listIndex < _types.length) 
		{
			var request:BasecampRequest = CategoryHelper.list(
			projectId, _types[_listIndex]);
			_listIndex += 1;	
			
			loader.load(request);
		}
		else super.loader_OKComplete(null);
	}
	
	private function loader_OKDelete(e:BasecampAPIEvent):void
	{
		_categoryId = null;
		super.cleanUp();
	}
	
	private function loader_OKPrepare(e:BasecampAPIEvent):void
	{
		var catXML:XML = e.data;
		catXML.name = new Date().toUTCString();
		
		super.initializeLoader(loader_OKCreate);
		loader.load(CategoryHelper.create(catXML));		
	}
	
	private function loader_OKCreate(e:BasecampAPIEvent):void
	{
		_categoryId = TestHelpers.parseForIdFromResponseHeaders(
		e.responseHeaders);
		super.self_CompleteInit(null);
	}
}
}